from datetime import datetime
import logging
from logging.handlers import TimedRotatingFileHandler

from pytz import timezone

from utils.mongo_util import db


async def save_data_log_mongo(data):
    try:
        beijing_tz = timezone('Asia/Shanghai')
        date = datetime.fromtimestamp(data['timestamp'], beijing_tz)
        data['date'] = date
        db.wristband_log.insert_one(data)
    except Exception as e:
        logger.error(str(e))


async def save_data_log_s8_mongo(data):
    try:
        db.wristband_log_s8.insert_one(data)
    except Exception as e:
        logger.error(str(e))


async def save_data_log_s8_health_mongo(data):
    try:
        db.wristband_log_s8_health.insert_one(data)
    except Exception as e:
        logger.error(str(e))


def configure_logging():
    # 配置根 Logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    logger.handlers.clear()

    # 文件 Handler（按天切割）
    file_handler = TimedRotatingFileHandler(
        filename="app.log",
        when="midnight",
        backupCount=7,
        encoding="utf-8",
        utc=False
    )
    # 控制台 Handler
    console_handler = logging.StreamHandler()

    # 统一格式
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)

    # 添加 Handler
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)


# 初始化配置
configure_logging()

# 模块级 Logger（自动继承根配置）
logger = logging.getLogger(__name__)
logger.info(" 日志配置测试成功")